package ca.cbc.msb.console.transaction;

import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import ca.cbc.medialib.dao.CategoryDAO;
import ca.cbc.medialib.entity.Category;

@Named
public class CategoryTransaction {
	protected Logger logger = LoggerFactory.getLogger(this.getClass());
	@Inject
	private CategoryDAO categoryDAO;

	@Transactional
    public boolean remove(long categoryId) {
		Category category = categoryDAO.findById(categoryId);
		if(category == null) {
			return true;	//category has been deleted by msb
		} else if (category.getMedias().size() != 0 || category.getChildren().size() != 0) {
			return false;	//category has children/medias
		}
		
    	categoryDAO.deleteById(categoryId);
    	return true;
    }
	
	@Transactional
	public TreeNode getTreeNode() {
		List<Category> parents = categoryDAO.listParents();
		
		TreeNode root = new DefaultTreeNode("root", null);
		for(Category cat : parents) {
			TreeNode child = new DefaultTreeNode(cat, root);
			buildTreeNode(child);
		}
		
		return root;
	}
	
	private void buildTreeNode(TreeNode root) {
		if(root == null) return;
		Category cat = (Category) root.getData();
		for(Category c : cat.getChildren()) {
			TreeNode child = new DefaultTreeNode(c, root);
			buildTreeNode(child);
		}
	}
	
	/**
	 * This function load all the medias and sponsors assigned to this category
	 * @param id
	 * @return 
	 */
	@Transactional
	public Category load(long id) {
		Category cat = categoryDAO.findById(id);
		if(cat != null) {
			cat.getMedias().size();		//initialize medias
			cat.getSponsors().size();	//initialize sponsors
		}
		return cat;
	}
}
